//
//  OPAuthUser.m
//  OPFramework
//
//  Created by malcom on 7/16/08.
//  Copyright 2008 malcom-mac software. All rights reserved.
//

#import "OPAuthUser.h"
#import "OPBoard.h"

@implementation OPAuthUser

@synthesize user_username;
@synthesize user_password;
@synthesize user_loginDate;
@synthesize user_personalBox;

- (id) initWithUsername:(NSString *) _user andPassword:(NSString *) _password {
	self = [super initWithUsername: _user andID: [NSNumber numberWithInt: -1] ofBoard: nil];
	if (self != nil) {
		user_username = [_user retain];
		user_password = [_password retain];
		//[self setLoginDateTo: nil];
		[self setLoginDateTo: [NSDate dateWithNaturalLanguageString: @"2008/05/24 03:41 AM"]];
		
	}
	return self;
}

- (void) setLoginDateTo:(NSDate *) _date {
	[user_loginDate release];
	if (_date == nil) user_loginDate = [[NSDate date] retain];
	else user_loginDate = [_date retain];
}

- (void) reloadAuthPersonalDatabase {
	if (user_personalBox == nil) 
		user_personalBox = [[OPPersonalInbox alloc] _initWithAuthorizedUser:self];
	// load data
	[user_personalBox refreshData];
}

- (NSString *) description {
	return [NSString stringWithFormat: @"OPAuthUser: %@, %d unread private messages",user_username,user_personalBox.p_unread_privateMsgs];
}

- (BOOL) isLogged {
	return user_username != nil && user_password != nil;
}

- (void) dealloc {
	[user_username release];
	[user_password release];
	[super dealloc];
}

- (int) unreadPrivateMessages {
	XMLRPCResponse *unreadMsgs = [_delegateBoard _executeRequestMethodNamed: @"user.countUnreadPrivateMessages"
																  withParams: nil
															  attachAuthData: NO];
	return [[unreadMsgs responseObject] intValue];
}

- (NSArray *) getOnlineFriends {
	XMLRPCResponse *onlineFriends = [_delegateBoard _executeRequestMethodNamed: @"user.getOnlineFriends"
																 withParams: nil
															 attachAuthData: NO];
	if ([onlineFriends isFault]) return nil;
	NSMutableArray *friends = [[NSMutableArray alloc] init];
	for (NSDictionary *cUser in [onlineFriends responseObject]) {
		OPUser *friend = [_delegateBoard.obj_membersCache getUserMemberFromID: [NSNumber numberWithInt: [[cUser objectForKey: @"user_id"] intValue]] 
								withName: [cUser objectForKey: @"username"]];
		NSDate *onlineSince = [NSDate dateWithTimeIntervalSince1970: [[cUser objectForKey:@"online_time"] longLongValue]];

		[friends addObject: [NSDictionary dictionaryWithObjectsAndKeys: friend,@"friend",onlineSince,@"online_since",nil]];
	}
	return [friends autorelease];
}

@end
